<?php
namespace app\api\service;

use app\api\model\store\Order as OrderModel;

use think\Db;
use think\Exception;
use think\Loader;
use think\Log;

Loader::import('WxPay.WxPay', EXTEND_PATH, '.Api.php');

class WxNotify extends \WxPayNotify{

    public function NotifyProcess($data, &$msg){

        Log::record($data, 'pay');
        if ($data['result_code'] == 'SUCCESS') {
            $orderNo = $data['out_trade_no'];
            Db::startTrans();
            try{
                Log::record($data, 'error');
                $time = time();

                $mOrderModel = new OrderModel();
                $order = $mOrderModel->where('order_no', $orderNo)->lock()->find();
                if ($order['order_status'] == 0) {
                    $order_id = $order['id'];
                    $order_no = $order['order_no'];
                    $user_id = $order['user_id'];
                    //更新订单数据
                    Db::name('store_order')->where('id', $order_id)->update([
                        'order_status' => 1,
                        'trade_id' => $data['transaction_id'],
                        'pay_status' => 1,
                        'pay_time' => $time,
                        'pay_content' => json_encode($data),
                        'update_time' => $time
                    ]);

                    /*************************订单操作表 start ***************************************/
                    Db::name('store_order_record')->insert([
                        'order_id' => $order_id,
                        'type' => 'pay_success',
                        'msg' => '用户付款成功',
                        'create_time' => $time,
                        'update_time' => $time,
                    ]);
                    //用户购买成功后 推送消息给用户
                    //$sSubscribeSerice = new SubscribeSerice();
                    //$sSubscribeSerice->paySuccessSend($order_id);
                }
                Db::commit();
            }catch (Exception $ex){
                Db::rollback();
                Log::record($ex, 'payerror');
                // 如果出现异常，向微信返回false，请求重新发送通知
                return false;
            }
        }
        return true;
    }


}